<template>
  <!-- <div>
      <CurrencyButton
        class="return"
        title="返回"
        type="primary"
        icon="DsrzReturn"
        @click="emit('close')"
      />
      <el-scrollbar class="scrollbar">
          <div class="form-box" style=" padding: 0 20px;" >
          </div>
      </el-scrollbar>
      <div class="footer">
          <CurrencyButton title="取消" :text="true" @click="handleCancel" />
          <CurrencyButton title="确定" type="primary" @click="handleConfirm" />
      </div>
  </div> -->

    <CurrencyDetails @cancel="handleCancel" @confirm="handleConfirm">
        <template #header  >
            <div class="flex aic jcc scrollbar-title">
                <div class="flex aic jcc scrollbar-title">{{ params.title }} </div>
            </div>
        </template>
        <CurrencyCard
            :items="card.items"
            :params="formSerach"
        />
    </CurrencyDetails>
</template>

<script lang="ts" setup>
import { ref, reactive, } from 'vue';
// import VisitorCard from '@/components/visitor/card/index.vue'
import type { KeysProps } from '../types/index'
import { aesDecrypt, aesEncrypt, refs } from 'dsrz/utils';
import { build, campus, comeItems, editOptions, getClassList, rules, card } from './addOrEdit';
// import { addStudentList, editStudentList, getStudentBuildList, getStudentDetail, getStudentRoomList } from '@/api/staffManagement';

defineOptions({
  name: 'addOrEditStudent',
})
const hostelSelectVal = ref({})
const emit = defineEmits(['close', 'success'])
const formSerach = reactive({
  nickname:'',
  sex: '',
  username:'',
  phone:'',
  nation:'',
  status:'' as string | number,
  polityIdentity:'',
  belief:'',
  gradeId:'' as unknown,
  classId:'',
  roomId:'',
  practice: false,
  birthDate:'',
  enable: true,
  fatherTel:'',
  motherTel:'',
  address: '',
  campusId: '' as unknown | number,
  buildId: '' as unknown | number
})
const statusMap: Record<string, number> = {
  WBD: 0,
  ZJ: 1,  
  BLXJ: 2,
  XX: 3,  
  TX: 4,  
  BY: 5,  
  JY: 6,  
  RW: 7,
  YBD: 9
};
const handelStatus = (status: string) => { 
    return statusMap[status] >= 0 ? statusMap[status] : '';
}

const params = reactive<KeysProps>({})
const getParams =async (val: KeysProps = {}) => { 
  if (val.id !== null && val.id !== undefined) {
    const res = await getStudentDetail({ id: val.id })
    for (const key in res.data) {
      // @ts-expect-error-回显数据
      formSerach[key] = res.data[key]
    }
    formSerach.nickname = aesDecrypt(formSerach.nickname)
    formSerach.username = aesDecrypt(formSerach.username)
    formSerach.phone = aesDecrypt(formSerach.phone)
    // @ts-expect-error-handelStatus
    formSerach.status = handelStatus(formSerach.status)
    formSerach.fatherTel = aesDecrypt(formSerach.fatherTel)
    formSerach.motherTel = aesDecrypt(formSerach.motherTel)
    const getOptions1 = await getStudentBuildList({
      campusId: formSerach.campusId,
      buildType: 1
    })
    const getOptions2 = await getStudentRoomList({
        campusId: formSerach.campusId,
        buildId: formSerach.buildId
    })
    const options1 = getOptions1.data.map((item: {id: number, name: string}) => { 
      return {
        value: item.id,
        label: item.name
      }
    })
    const options2 = getOptions2.data.map((item: {id: number, name: string}) => { 
      return {
        value: item.id,
        label: item.name
      }
    })
    editOptions({
      options1,
      options2
    })
    getClassList(formSerach.gradeId as number)
    hostelSelectVal.value = {
      campusId: formSerach.campusId,
      buildId: formSerach.buildId,
      roomId: formSerach.roomId
    }
  }
  Object.assign(params, val)
}

const handleCancel = () => { 
  for (const key in formSerach) {
    // @ts-expect-error-清空表单
    formSerach[key] = key === 'practice' ? false : key === 'enable' ? true : ''
  }
  emit('close')
}

const handleConfirm = async() => { 
  console.log('222', formSerach)
  
  // 准备数据
  const data = {
    ...formSerach
  }
  data.nickname = aesEncrypt(data.nickname)
  data.username = aesEncrypt(data.username)
  data.phone = aesEncrypt(data.phone)
  data.fatherTel = aesEncrypt(data.fatherTel)
  data.motherTel = aesEncrypt(data.motherTel)
  data.campusId = campus.value ?? data.campusId
  data.buildId = data.campusId === 0 ? '' : build.value ?? data.buildId
  data.roomId = data.campusId === 0 ? '' : data.roomId
  
  // 执行表单校验
  try {
    await refs.InfoRef.validate(async (valid: boolean) => { 
      if(!valid) {
        console.log('== 表单校验失败')
        return
      }
      
      console.log('== 表单校验通过，开始提交数据')
      
      // 额外的业务校验
      if (data.campusId !== 0 && String(data.roomId).length <= 0) {
        console.log('== 请选择宿舍信息')
        // 这里可以添加消息提示
        return
      }
      
      // 根据操作类型执行不同的逻辑
      if (params.action === 'add') {
        console.log('== 执行新增操作')
        const res = await addStudentList(data)
        if (res.code === 200) {
          console.log('== 新增成功')
          handleCancel()
          emit('success')
        }
      } else { 
        console.log('== 执行编辑操作')
        const res = await editStudentList(data)
        if (res.code === 200) {
          console.log('== 编辑成功')
          handleCancel()
          emit('success')
        }
      }
    })
  } catch (error) {
    console.error('== 表单校验或提交过程中发生错误:', error)
  }
}
const clearRoomId = () => { 
  formSerach.roomId = ''
}
type FormSearchKey = keyof typeof formSerach;
type FormSearchValue<T extends FormSearchKey> = typeof formSerach[T];
const clearFrmSerachData = <T extends FormSearchKey>(key: T, value: FormSearchValue<T>) => {
  formSerach[key] = value;
};

defineExpose({
  getParams,
  clearRoomId,
  hostelSelectVal,
  clearFrmSerachData
})
</script>

<style lang="scss" scoped>
.return {
  margin: 16px 0 16px 10px;
}
.scrollbar {
  height: calc(100vh - var(--dsrz-header-height) - 190px);
  &-title {
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: bold;
    font-size: 14px;
    color: var(--dsrz-theme-color);
    line-height: 24px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    height: 24px;
  }
}
.form-box {
  ::v-deep(.el-date-editor) {
    --el-date-editor-width: var(--dsrz-form-width) !important;
  }
}
.footer {
  display: flex;
  justify-content: flex-end;
  margin: 16px 42px 0 42px;
}
</style>
